import { Fragment, useEffect, useState, useCallback } from 'react'
import { NavLink, useNavigate } from 'react-router-dom'
import { Table, Tag, Button, message, Modal } from 'antd'
import { RocketOutlined, RollbackOutlined, HighlightOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { http } from '@/utils/http'
const { confirm } = Modal;

export default function AuditList() {
  const navigate = useNavigate()
  const [auditArr, setAuditArr] = useState([])  // 审核列表文章数据
  const [category, setCategory] = useState([])  // 新闻分类
  // 从token中拿到当前登录用户的username
  const { username } = JSON.parse(window.sessionStorage.getItem('news'))
  // 获取审核列表中的文章数据数组
  const getAuditArr = useCallback(async () => {
    // auditState_ne=0 代表 筛选auditState 不等于0的项
    // lte是小于 gte是大于
    // 请求所有新闻中，作者是当前登录用户，auditState不等于0，publishState小于等于1
    const { data } = await http.get(`/news?auditState_ne=0&author=${username}&publishState_lte=1`)
    setAuditArr(data)
  }, [username])

  // 获取新闻分类信息列表
  const getCategoryList = async () => {
    const { data } = await http.get('/categories')
    setCategory(data)
  }

  useEffect(() => {
    getAuditArr()
    getCategoryList()
  }, [getAuditArr])

  // 输入文章分类id找到对应的文章分类名
  const findCategoryName = id => {
    return category?.find(item => item.id === id)?.title
  }

  // 操作区
  // 撤销
  const onClickRollback = id => {
    http.patch(`/news/${id}`, {
      auditState: 0
    })
      .then(() => {
        setAuditArr(auditArr.filter(item => item.id !== id))
        message.success('撤销操作成功！', 2)
        navigate('/news-manage/draft')
      })
      .catch(() => {
        message.error('request失败！', 2)
      })
  }

  // 发布
  const onClickPublish = id => {
    confirm({
      title: '您确定要发布此文章吗？',
      icon: <ExclamationCircleOutlined />,

      onOk() {
        return new Promise((resolve, reject) => {
          onClickPublishOk(resolve, reject, id)
        })
      },
      onCancel() {
        message.info('您取消了该操作！', 2)
      },
    });
  }

  // 点击发布确定的回调
  const onClickPublishOk = (resolve, _, id) => {
    http.patch(`/news/${id}`, {
      publishState: 2,
      publishTime: Date.now()  // 发布时间
    })
      .then(() => {
        resolve()
        message.success('发布成功！', 2)
        navigate('/publish-manage/published')
      })
      .catch(() => {
        resolve()
        message.error('发布失败！', 2)
      })
  }

  // 修改
  const onClickEdit = id => {
    navigate(`/news-manage/update/${id}`)
  }

  const columns = [
    {
      title: '新闻标题',
      dataIndex: 'title',
      align: 'center',
      width: '360px',
      ellipsis: true,
      render: (title, { id }) => {
        return <NavLink to={`/news-manage/preview/${id}`} >{title}</NavLink>
      }
    },
    {
      title: '作者',
      dataIndex: 'author',
      align: 'center',
    },
    {
      title: '新闻分类',
      dataIndex: 'categoryId',
      align: 'center',
      render: categoryId => findCategoryName(categoryId)
    },
    {
      title: '审核状态',
      dataIndex: 'auditState',
      align: 'center',
      render: auditState => {
        if (auditState === 1) {
          return <Tag color="warning">审核中</Tag>
        } else if (auditState === 2) {
          return <Tag color="success">已通过</Tag >
        } else if (auditState === 3) {
          return <Tag color="error">未通过</Tag>
        }
      }
    },
    {
      title: '操作',
      align: 'center',
      render: ({ auditState, id }) => {
        if (auditState === 1) {
          return <Button type="primary" icon={<RollbackOutlined />} onClick={() => onClickRollback(id)}>撤销</Button>
        } else if (auditState === 2) {
          return <Button type="primary" icon={<RocketOutlined />} onClick={() => onClickPublish(id)}>发布</Button>
        } else if (auditState === 3) {
          return <Button type="primary" icon={<HighlightOutlined />} onClick={() => onClickEdit(id)}>修改</Button>
        }
      }
    }
  ];

  return (
    <Fragment>
      <Table dataSource={auditArr} columns={columns} rowKey={item => item.id}></Table>
    </Fragment>
  )
}